package com.guoji.cameracall.helper

import android.graphics.ImageFormat
import android.graphics.Rect

import android.graphics.YuvImage
import android.os.Environment
import java.io.File
import java.io.FileOutputStream
import java.io.IOException



/**
 * create by zhongZihao on 2021/9/27
 */
object YuvUtil {
    private var nv12Temp: ByteArray? = null

    //nv21转nv12
    fun nv21ToNv12(nv21: ByteArray): ByteArray {
        val size = nv21.size
        nv12Temp = ByteArray(size)
        val len = nv21.size * 2 / 3
        System.arraycopy(nv21, 0, nv12Temp, 0, len)
        var i = len
        while (i < size - 1) {
            nv12Temp!![i] = nv21[i + 1]
            nv12Temp!![i + 1] = nv21[i]
            i += 2
        }
        return nv12Temp!!
    }

    //像素旋转
    fun portraitData2Raw(data: ByteArray, output: ByteArray, width: Int, height: Int) {
        val y_len = width * height
        val uvHeight = height shr 1 // uv数据高为y数据高的一半
        var k = 0
        for (j in 0 until width) {
            for (i in height - 1 downTo 0) {
                output[k++] = data[width * i + j]
            }
        }
        var j = 0
        while (j < width) {
            for (i in uvHeight - 1 downTo 0) {
                output[k++] = data[y_len + width * i + j]
                output[k++] = data[y_len + width * i + j + 1]
            }
            j += 2
        }
    }

    //保存YUV数据为图片
    fun captrue(temp: ByteArray?, width: Int, height: Int) {
        temp ?: return
        //保存一张照片
        val fileName = "IMG_${System.currentTimeMillis()}.jpg" //jpeg文件名定义
        val sdRoot: File = Environment.getExternalStorageDirectory() //系统路径
        val pictureFile = File(sdRoot, fileName)
        if (!pictureFile.exists()) {
            try {
                pictureFile.createNewFile()
                val filecon = FileOutputStream(pictureFile)
                //ImageFormat.NV21 and ImageFormat.YUY2 for now
                val image = YuvImage(
                    temp,
                    ImageFormat.NV21,
                    width,
                    height,
                    null
                ) //将NV21 data保存成YuvImage
                //图像压缩
                image.compressToJpeg(
                    Rect(0, 0, image.width, image.height),
                    100, filecon
                ) // 将NV21格式图片，以质量70压缩成Jpeg，并得到JPEG数据流
            } catch (e: IOException) {
                e.printStackTrace()
            }
        }
    }

}